package leeon.words;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class SearchUtil {
	
	@SuppressWarnings({ "rawtypes" })
	public static List<String> search(String content, Map index) {
		List<String> ret = new ArrayList<String>();
		char[] cs = content.toCharArray();
		for (int i = 0; i < cs.length; i ++) {
			int e = searchFromI(cs, i, index);
			if (e != -1) {
				ret.add(String.valueOf(cs, i, e-i)+","+i+","+e);
				i = e-1;
			}
		}
		return ret;
	}
	
	@SuppressWarnings("rawtypes")
	private static int searchFromI(char[] cs, int i, Map index) {
		if (i == cs.length) return -1;
		
		if (index.containsKey(cs[i])) {
			Object v = index.get(cs[i]);
			if (v instanceof Map) {
				return searchFromI(cs, ++i, (Map)v);
			} else {
				return searchFromS(cs, i, (String)v);
			}
		} else {
			return -1;
		}
	}
	
	private static int searchFromS(char[] cs, int i, String v) {
		String v1 = String.valueOf(cs, i+1, v.length());
		return !v1.equals(v)?-1:(i+1+v.length());
	}
	
	public static String readFile(String path) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(path), "Unicode"));
		StringBuffer sb = new StringBuffer();
		int max = 0;
		char[] buffer = new char[1024];
		while ((max = in.read(buffer)) != -1) {
			sb.append(buffer, 0, max);
		}
		in.close();
		return sb.toString();
	}
	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) throws IOException {
		DictIndex d = new DictIndex("C:\\users\\study\\desktop\\moive_dict.txt");
		String content = readFile("C:\\users\\study\\desktop\\content.txt");
		System.out.println(content);
		List<String> ret = search(content, d.getDictIndex());
		System.out.println(ret);
	}

}
